package com.lyy.weather.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.lyy.weather.R;
import com.lyy.weather.TIme.TimeUtil;
import com.lyy.weather.TIme.Timerr;
import com.lyy.weather.bean.AirIndices;
import com.lyy.weather.bean.City;
import com.lyy.weather.bean.LifeIndices;
import com.lyy.weather.bean.RefreshableView;
import com.lyy.weather.bean.ThreadFlag;
import com.lyy.weather.bean.WeatherDaily;
import com.lyy.weather.bean.WeatherHourly;
import com.lyy.weather.bean.WeatherTimely;
import com.lyy.weather.database.DatabaHelper;
import com.lyy.weather.database.DatabaseUtil;
import com.lyy.weather.database.LayoutUtil;
import com.lyy.weather.database.RefreshUtil;

import com.lyy.weather.database.WeatherDataUtil;
import com.lyy.weather.fragment.WeatherFragment;
import com.lyy.weather.layout.adapter.WholeAdapter;
import com.lyy.weather.layout.bean.AirIndicesItem4;
import com.lyy.weather.layout.bean.CityChange;
import com.lyy.weather.layout.bean.LifeIndicesItem5;
import com.lyy.weather.layout.bean.MainItem;
import com.lyy.weather.layout.bean.RecyclerItem2;
import com.lyy.weather.layout.bean.RecyclerItem3;
import com.lyy.weather.layout.bean.Type;
import com.lyy.weather.layout.bean.WeatherDailyItem3;
import com.lyy.weather.layout.bean.WeatherHourlyItem2;
import com.lyy.weather.network.HttpUtil;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private DatabaHelper dbHelper;
    private String DEFAULT_CITY="101280101";//默认城市为广州
    private DatabaseUtil databaseUtil;
    private LayoutUtil layoutUtil;
    public static final int REFRESH_ALL=10001;
    public static final int START=10002;
    public static final int PREPARE=10003;
    public static final int CHANGE=10004;
    private boolean preparation=false;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout refreshLayout;
    private Intent intentChange;
   private WholeAdapter wholeAdapter;
   private MainItem item1;
    private RecyclerItem2 item2;
   private RecyclerItem3 item3;
   private AirIndicesItem4 item4;
   private LifeIndicesItem5 item5;
   private ThreadFlag threadFlag;
   private List<WeatherHourlyItem2> weatherHourlyItem2List;
   private List<WeatherDailyItem3> weatherDailyItem3List;
   private String nowLocationId=DEFAULT_CITY;


   private List<Type> itemList;
    private Handler handler=new Handler(Looper.getMainLooper()){
        //重写父类的handleMessage方法，在这里对具体的Message进行处理
        public void handleMessage(Message msg){
            switch (msg.what){//对比msg.what字段的值

                case PREPARE:{
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    HttpUtil httpUtil=new HttpUtil("guangzhou",HttpUtil.MyRequestType.CITY_REQUEST,
                                            MainActivity.this,dbHelper);
                                    httpUtil.getDataFromApi();
                                    Message message=new Message();
                                    //指定what字段
                                    message.what=REFRESH_ALL;
                                    //发送message
                                    handler.sendMessage(message);
                                }
                            }).start();


                        }
                    }).start();
                }
                    break;
                case REFRESH_ALL: {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        Log.d("TAG", "run: ");
                        databaseUtil.deleteAll();
                    //    List<String> locationIdList = databaseUtil.getAlllocationId();
                        //下面遍历城市编号，更新数据
                       // Iterator<String> iterator = locationIdList.iterator();

                      //  while (iterator.hasNext()) {
                           // String locationId = iterator.next();
                            HttpUtil httpUtil = new HttpUtil(DEFAULT_CITY, HttpUtil.MyRequestType.ALL_DATA_REQUEST, databaseUtil.getmContext(),
                                    databaseUtil.getDbHelper());

                            httpUtil.getDataFromApi();
                       // }


                        Message message=new Message();
                        //指定what字段
                        message.what=START;
                        databaseUtil.addTime();
                        Log.d("TAG", "RefreshAll: finished~~");
                        //发送message
                        handler.sendMessage(message);
                    }
                }).start();


                }
                break;
                case START:{
                    progressDialog.dismiss();
                    //toolbar获取实例
                    Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
                    //传入实例
                    setSupportActionBar(toolbar);
                   // showWeather(DEFAULT_CITY);
                    replaceFragment(new WeatherFragment());
                    break;}
                case CHANGE:
                {    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            changeWeather(nowLocationId);
                        }
                    });
                    break;}
                default:
                    break;
            }

        }
    };



    public MainItem setDataInMainItem(String locationId){
        City city=(City) databaseUtil.searchCity(locationId);
        WeatherTimely weatherTimely=(WeatherTimely)databaseUtil.searchWeatherTimely(locationId);
        List<WeatherDaily> weatherDailyList=databaseUtil.searchWeatherDaily(locationId);
        AirIndices airIndices=(AirIndices)databaseUtil.searchAirIndices(locationId);
        //LayoutUtil layoutUtil=new LayoutUtil(databaseUtil,"101280101");
        MainItem mainItem=new MainItem();
        mainItem.setCity(city.getName());
        mainItem.setTempMaxAndMin(weatherDailyList.get(0).getTempMax()+"/"+
                weatherDailyList.get(0).getTempMin()+"℃");
        mainItem.setTemperature(weatherTimely.getTemp());
        mainItem.setAirCategory(airIndices.getCategory());
        return mainItem;
    }
    public List<WeatherHourlyItem2> setDataInItem2(String locationId){
       // TimeUtil timeUtil=new TimeUtil();
        List<WeatherHourly> hourlyList=databaseUtil.searchWeatherHourly(locationId);
        Iterator<WeatherHourly> it=hourlyList.iterator();
        List<WeatherHourlyItem2> item2List=new ArrayList<>();//要返回的表
        while(it.hasNext()){
            WeatherHourly hourly=it.next();
            WeatherHourlyItem2 item2=new WeatherHourlyItem2();
            item2.setPicId(hourly.getIcon());
            item2.setTemperature(hourly.getTemp()+"℃");

            Date date= null;
            try {
                date = TimeUtil.getDateInFormat(hourly.getFxTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String time=TimeUtil.getHourlyString(date);
            item2.setTime(time);
            item2List.add(item2);
        }
        return item2List;
    }
    public List<WeatherDailyItem3> setDataInItem3(String locationId){
        List<WeatherDaily> dailyList=databaseUtil.searchWeatherDaily(locationId);
        Iterator<WeatherDaily> it=dailyList.iterator();
        List<WeatherDailyItem3> item3List=new ArrayList<>();//要返回的表
        while ((it.hasNext())){
            WeatherDaily daily=it.next();
            WeatherDailyItem3 item3=new WeatherDailyItem3();
            item3.setPicId(daily.getIconDay());
            item3.setTempMax(daily.getTempMax());
            item3.setTempMin(daily.getTempMin());
            item3.setWeatherText(daily.getTextDay());

            item3.setDate(daily.getFxDate());
            item3List.add(item3);
        }
        return item3List;
    }
    public AirIndicesItem4 setDataInItem4(String locationId){
        AirIndices airIndices=(AirIndices)databaseUtil.searchAirIndices(locationId);
        AirIndicesItem4 item4=new AirIndicesItem4();//要返回的值
        item4.setAqi(airIndices.getAqi());
        item4.setCategory(airIndices.getCategory());
        item4.setCo(airIndices.getCo());
        item4.setNo2(airIndices.getNo2());
        item4.setSo2(airIndices.getSo2());
        item4.setO3(airIndices.getO3());
        item4.setPm2p5(airIndices.getPm2p5());
        item4.setPm10(airIndices.getPm10());

        return item4;
    }
    public LifeIndicesItem5 setDataInItem5(String locationId){
        LifeIndices lifeIndices=(LifeIndices)databaseUtil.searchLifeIndices(locationId);
        List<LifeIndices.DifferentIndices> indicesList=lifeIndices.getIndicesList();
        LifeIndicesItem5 item5=new LifeIndicesItem5();//要返回的值
        Iterator<LifeIndices.DifferentIndices> it=indicesList.iterator();
        while(it.hasNext()){
            LifeIndices.DifferentIndices differentIndices=it.next();
            switch (differentIndices.getType()){
                case 1:
                    item5.setSport(differentIndices.getCategory());
                    break;
                case 3:
                    item5.setDressing(differentIndices.getCategory());
                    break;
                case 4:
                    item5.setFishing(differentIndices.getCategory());
                    break;
                case 5:
                    item5.setUv(differentIndices.getCategory());
                    break;
                case 6:
                    item5.setJourney(differentIndices.getCategory());
                    break;
                case 7:
                    item5.setPollen(differentIndices.getCategory());
                    break;
                case 8:
                    item5.setComfort(differentIndices.getCategory());
                    break;
                case 9:
                    item5.setGetCold(differentIndices.getCategory());
                    break;
                case 10:
                    item5.setAirPollution(differentIndices.getCategory());
                    break;
                case 11:
                    item5.setAirConditionor(differentIndices.getCategory());
                    break;
                case 12:
                    item5.setSunglass(differentIndices.getCategory());
                    break;
                case 13:
                    item5.setMakeup(differentIndices.getCategory());
                    break;

            }

        }
        return item5;
    }
    public void refreshAll(){
        List<String> locationIdList=databaseUtil.getAlllocationId();
        //删除数据库中除城市信息外的所有表的数据
        //下面遍历城市编号，更新数据
        Iterator<String> iterator=locationIdList.iterator();
        String locationId;
        while(iterator.hasNext()){
            locationId=iterator.next();
            HttpUtil httpUtil=new HttpUtil(locationId,HttpUtil.MyRequestType.ALL_DATA_REQUEST,databaseUtil.getmContext(),databaseUtil.getDbHelper());
            httpUtil.getAllDataOfSpecificLocation();
        }

        databaseUtil.addTime();
        Log.d("TAG", "RefreshAll: finished~~");
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
/*
        refreshLayout=(SwipeRefreshLayout)findViewById(R.id.refresh_layout);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //先更新当前城市的数据库
                //先删除
                databaseUtil.deleteLocationIdInfo(nowLocationId);
                //再添加
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpUtil httpUtil = new HttpUtil(nowLocationId, HttpUtil.MyRequestType.ALL_DATA_REQUEST, databaseUtil.getmContext(),
                                databaseUtil.getDbHelper());
                        httpUtil.getDataFromApi();
                        //更换新碎片
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                replaceFragment(new WeatherFragment());
                                refreshLayout.setRefreshing(false);
                                Toast.makeText(MainActivity.this, "刷新成功~", Toast.LENGTH_SHORT).show();
                            }
                        });


                    }
                }).start();


            }

        });
        refreshLayout.setProgressViewOffset(true, -0, 100);
        refreshLayout.setOnChildScrollUpCallback(null);

*/

        progressDialog=new ProgressDialog(MainActivity.this);
        progressDialog.setTitle("数据加载中");
        progressDialog.setMessage("请稍等....");
        progressDialog.setCancelable(false);
        progressDialog.show();
        //创建数据库
       // HttpUtil httpUtil=new HttpUtil("guangzhou",HttpUtil.MyRequestType.CITY_REQUEST,MainActivity.this,
             //   dbHelper);
        //httpUtil.getDataFromApi();

        //TimeUtil timeUtil = new TimeUtil();

        dbHelper = new DatabaHelper(MainActivity.this, "WeatherInformation.db", null, 31,handler);
        dbHelper.getWritableDatabase();
        databaseUtil = new DatabaseUtil(MainActivity.this, dbHelper);
        SQLiteDatabase db=dbHelper.getReadableDatabase();
        Cursor cursor=db.query("City",null,null,null,null,null
        ,null);
        if(!cursor.moveToFirst()){
            Message message=new Message();
            //指定what字段
            message.what=PREPARE;
            //发送message
            handler.sendMessage(message);
        }else{
            Message message=new Message();
            //指定what字段
            message.what=REFRESH_ALL;
            //发送message
            handler.sendMessage(message);
        }




    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //加载菜单文件
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            //处理各个按钮的点击事件
            case R.id.adding:
                //进入搜索城市的界面

                break;
            case R.id.setting:
                intentChange=new Intent(MainActivity.this, ChangeCityActivity.class);
                startActivityForResult(intentChange,1);
                break;
            default:
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK)//判断处理结果是否成功
                {  //从data中取值
                    nowLocationId = data.getStringExtra("locationId");
                    Toast.makeText(MainActivity.this,nowLocationId,Toast.LENGTH_SHORT)
                            .show();



                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HttpUtil httpUtil = new HttpUtil(nowLocationId, HttpUtil.MyRequestType.ALL_DATA_REQUEST, databaseUtil.getmContext(),
                                    databaseUtil.getDbHelper());
                            httpUtil.getDataFromApi();

                            replaceFragment(new WeatherFragment());
                        }
                    }).start();

                }
                break;
            default:
        }
    }

    private void showWeather(String locationId){
        progressDialog.dismiss();
        //toolbar获取实例
        Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
        //传入实例
        setSupportActionBar(toolbar);
        //调试用，组装子项数据
        WeatherHourlyItem2 weatherHourlyItem2=new WeatherHourlyItem2();
        WeatherDailyItem3 weatherDailyItem3=new WeatherDailyItem3();
        //运行起main RecyclerView
        //组装数据
        weatherHourlyItem2List=new ArrayList<>();
        weatherHourlyItem2List=setDataInItem2(locationId);

         weatherDailyItem3List=new ArrayList<>();
        weatherDailyItem3List=setDataInItem3(locationId);

        //获取子项数据
         item1=new MainItem();
        item1=setDataInMainItem(locationId);

        item2=new RecyclerItem2(weatherHourlyItem2List);
        item3=new RecyclerItem3(weatherDailyItem3List);
         item4=new AirIndicesItem4();
        item4=setDataInItem4(locationId);
         item5=new LifeIndicesItem5();
        item5=setDataInItem5(locationId);

        //装到表里~
        itemList=new ArrayList<>();
        itemList.add(item1);
        itemList.add(item2);
        itemList.add(item3);
        itemList.add(item4);
        itemList.add(item5);

        ListView recyclerView=(ListView)findViewById(R.id.main_list_view);
        //LayoutManager用于指定RecyclerView的布局方式，这里使用的是线性布局，可以实现和ListView类似的效果
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        // recyclerView.setLayoutManager(layoutManager);
        //创建适配器实例，将子项数据传入
        WholeAdapter wholeAdapter=new WholeAdapter(this,itemList,databaseUtil,dbHelper);
        //设置适配器，完成关联
        recyclerView.setAdapter(wholeAdapter);
        /**/

    }

    private void changeWeather(String locationId){
//调试用，组装子项数据
        //加载更换的城市数据

        itemList.clear();
        MainItem item1=new MainItem();
        item1=setDataInMainItem(nowLocationId);
        // weatherHourlyItem2List=new ArrayList<>();
        //List<WeatherHourlyItem2> weatherHourlyItem2List=new ArrayList<>();
        List<WeatherHourlyItem2> changeList2=setDataInItem2(nowLocationId);
        List<WeatherDailyItem3> changeList3=setDataInItem3(nowLocationId);
        weatherHourlyItem2List.clear();
        Iterator<WeatherHourlyItem2> it2=changeList2.iterator();
        while(it2.hasNext()){
            WeatherHourlyItem2 weatherHourlyItem2=it2.next();
            weatherHourlyItem2List.add(weatherHourlyItem2);
        }
        weatherDailyItem3List.clear();
        Iterator<WeatherDailyItem3> it3=changeList3.iterator();
        while(it2.hasNext()){
            WeatherDailyItem3 weatherDailyItem3=it3.next();
            weatherDailyItem3List.add(weatherDailyItem3);
        }
        //weatherHourlyItem2List=setDataInItem2(nowLocationId);
      //  List<WeatherDailyItem3> weatherDailyItem3List=new ArrayList<>();
        //weatherDailyItem3List=setDataInItem3(nowLocationId);

        AirIndicesItem4 item4;
        LifeIndicesItem5 item5;

      // RecyclerItem2 item2=new RecyclerItem2(weatherHourlyItem2List);
      // RecyclerItem3 item3=new RecyclerItem3(weatherDailyItem3List);
        item2.setList(weatherHourlyItem2List);
        item3.setList(weatherDailyItem3List);
        // item4=new AirIndicesItem4();
         item4=setDataInItem4(nowLocationId);
        //  item5=new LifeIndicesItem5();
        item5=setDataInItem5(nowLocationId);
        itemList.add(item1);
        itemList.add(item2);
        itemList.add(item3);
        itemList.add(item4);
        itemList.add(item5);
        // wholeAdapter.setDataList(itemList);
        Log.d("TAG,",item1.toString());



      wholeAdapter.notifyDataSetChanged();



    }

    public void replaceFragment(Fragment fragment){
        //2.获取FragmentManager，在活动中可以直接通过调用getSupportFragmentManager()得到
        FragmentManager fragmentManager=getSupportFragmentManager();
        //3.开启一个事务，通过调用beginTransaction()方法开启
        FragmentTransaction transaction=fragmentManager.beginTransaction();
        //4.向容器内添加或替换碎片，一般使用replace()方法实现，需要传入容器的id和待添加的碎片实例
        transaction.replace(R.id.weather_fragment_layout,fragment);
        //5.提交事务，调用commit()方法完成
        transaction.commit();
    }


    public String getNowLocationId() {
        return nowLocationId;
    }
}